package cn.dliyy.staff.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.dliyy.base.bean.Constant;
import cn.dliyy.base.service.KeyValueService;
import cn.dliyy.staff.bean.UStaff;
import cn.dliyy.staff.service.UStaffService;

@Controller
@RequestMapping(value = "/staff/user")
public class BStaffController {

  @Resource
  private UStaffService uStaffService;
  @Resource
  private UStaff ustaff;
  @Resource
  private KeyValueService kvService;

  @RequestMapping(value = { "", "/" })
  public String load(ModelMap modelMap) {
    List<?> list = uStaffService.getList(UStaff.class);
    modelMap.put("list", list);
    return "/staff/staff";
  }

  @RequestMapping(value = "/add", method = RequestMethod.GET)
  public String create(ModelMap modelMap) {
    Map<String, String> idmap = kvService.getMap(Constant.ID);
    modelMap.put("IDType", idmap);
    modelMap.put("ustaff", ustaff);
    return "/staff/staff_add";
  }

  @RequestMapping(value = "/add", method = RequestMethod.POST)
  public String create(@Valid @ModelAttribute("ustaff") UStaff ustaff, BindingResult result, ModelMap modelMap) {
    if (result.hasErrors()) {
      Map<String, String> idmap = kvService.getMap(Constant.ID);
      modelMap.put("IDType", idmap);
      return "/staff/staff_add";
    }
    uStaffService.save(ustaff);
    return "redirect:/staff/user";
  }

  @RequestMapping(value = { "/ajax/", "/ajax" }, method = RequestMethod.POST)
  @ResponseBody
  public Map<String, Object> load(@RequestParam(value = "query") String name) {
    List<Object> ulist = uStaffService.getList(name);
    List<String> suggestions = new ArrayList<String>();
    List<UStaff> data = new ArrayList<UStaff>();
    Map<String, Object> map = new HashMap<String, Object>();
    if (ulist != null && ulist.size() > 0) {
      for (int i = 0; i < ulist.size(); i++) {
        UStaff tustaff = (UStaff) ulist.get(i);
        suggestions.add(tustaff.getName());
        data.add(tustaff);
      }
    }
    map.put("query", name);
    map.put("suggestions", suggestions);
    map.put("data", data);
    return map;
  }
}